package com.sgb.kjwl.view.ui.activity.manage

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.text.TextUtils
import android.view.View
import androidx.databinding.DataBindingUtil
import com.alibaba.sdk.android.vod.upload.VODUploadClientImpl
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityUpLoadBinding
import com.sgb.kjwl.di.self.DaggerSelfComponent
import com.sgb.kjwl.di.self.SelfModule
import com.sgb.kjwl.utils.GlideEngine
import com.sgb.link.utils.SizeUtils
import com.sgb.kjwl.view.event.self.LogoRefreshEvent
import com.sgb.kjwl.view.widget.manage.WebsiteUtils
import com.sgb.kjwl.viewmodel.manage.UpLoadViewModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.dialog.DialogHelper
import com.swgk.core.util.MToast
import com.swgk.core.util.SharedPreferenceUtil
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.util.*
import javax.inject.Inject

/**
 * 单图片上传
 *  或者视频上传
 */
class UpLoadActivity : AppActivity() {

    @Inject
    lateinit var mViewModel : UpLoadViewModel

    private lateinit var mBinding : ActivityUpLoadBinding
    private var mType = TYPE_PIC

    private var localVideoUrl = "" //本地视频url
    private var videoCoverUrl = ""

    private var siteNo = ""

    private var mWebsiteId = ""

    private var mWebsiteVideoId = ""

    private var mUpLoadPic = ""//上传的图片
    private var mUploadVideo = ""//上传的视频


    companion object{
        const val KEY_TYPE = "key_type"
        const val TYPE_PIC = 10032
        const val TYPE_VIDEO = 10033
        fun launch(context: Context, type : Int = TYPE_PIC){
            val intent = Intent(context, UpLoadActivity::class.java)
            intent.putExtra(KEY_TYPE, type)
            context.startActivity(intent)
        }
    }


    override fun setupActivityComponent(appComponent: AppComponent?) {
        super.setupActivityComponent(appComponent)
        DaggerSelfComponent.builder().appComponent(appComponent)
            .selfModule(SelfModule()).build().inject(this)
    }

    override fun initView() {
        super.initView()
        if (intent != null){
            mType = intent.getIntExtra(KEY_TYPE, TYPE_PIC)
        }
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_up_load)
        mBinding.include.titleView.text = if (TYPE_PIC == mType) "LOGO设计" else "视频展示"
        mBinding.include.ivBack.setOnClickListener { finish() }
        mBinding.starTv.visibility = if (TYPE_PIC == mType) View.VISIBLE else  View.GONE
        mBinding.tvTip.text = if (TYPE_PIC == mType) "LOGO设计" else "温馨提示 : 该上传视频会在网站首页,简介中展示"
        mBinding.tvTypeTip.text = resources.getString(if (TYPE_PIC == mType) R.string.upload_pic_tip else R.string.upload_pic_tip)
        mBinding.ivPic.setRoundCorner(SizeUtils.dp2px(1.5f), SizeUtils.dp2px(1.5f))
        if (mType == TYPE_VIDEO){
            mViewModel.setUploadClient(VODUploadClientImpl(applicationContext))
        }
        if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1) != 0){
            siteNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "")
        } else {
            siteNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "")
        }
        mBinding.rlContent.setOnClickListener {
            if (TYPE_PIC == mType){
                pictureSelector(true, 500, 1)
            } else {
                videoSelector(1, 336)
            }
        }
        mBinding.ivDelete.setOnClickListener {

            if (mType == TYPE_VIDEO){
                videoCoverUrl = ""
                localVideoUrl = ""
                uploadVideoResult("")
            } else if (mType == TYPE_PIC) {
                showAvatar("")
            }
        }
        mViewModel.mPicUrl.observe(this, {
            if (TextUtils.isEmpty(it)){
                MToast.showToast(this, "上传失败")
                return@observe
            }
            showAvatar(it)
        })
        mViewModel.mVideoUrl.observe(this, {
            if (!TextUtils.isEmpty(it)){
                uploadVideoResult(it)
            }
        })
        mViewModel.message.observe(this, {
            if (!TextUtils.isEmpty(it)){
                MToast.showToast(this, it)
                finish()
            }
        })
        mViewModel.mPicUrlResult.observe(this,{
            if (!TextUtils.isEmpty(it)){
                MToast.showToast(this, it)
                EventBus.getDefault().postSticky(LogoRefreshEvent.make())
                finish()
            }
        })
        mViewModel.mWebsiteInfoEntity.observe(this, {
            if (it != null){
                if (mType == TYPE_PIC) {
                    showAvatar(it.logo)
                    mWebsiteId = it.id
                }
            }
        })
        mViewModel.mAliVideoBean.observe(this,  {
            mWebsiteVideoId = if (TextUtils.isEmpty(it.id)) "" else it.id //编辑时
            if (it.playInfoList != null && it.playInfoList.isNotEmpty() && !TextUtils.isEmpty(it.playInfoList[it.playInfoList.size -1].playURL)){
                localVideoUrl = it.playInfoList[it.playInfoList.size -1].playURL
            }
            if (it.videoBase != null){
                if (!TextUtils.isEmpty(it.videoBase.coverURL)){
                    videoCoverUrl = it.videoBase.coverURL
                } else {
                    videoCoverUrl = ""
                }
                if (!TextUtils.isEmpty(it.videoBase.videoId)){
                    uploadVideoResult(it.videoBase.videoId)
                } else {
                    uploadVideoResult("")
                }
            }
        })

        mBinding.tvCommit.setOnClickListener {
            if (mType == TYPE_PIC){
                mViewModel.upLoadLogo(mWebsiteId, mUpLoadPic)
            } else if (mType == TYPE_VIDEO){
                mViewModel.saveOrUpdateWebsiteVideo(mWebsiteVideoId, mUploadVideo)
            }
        }
    }

    override fun init() {
        super.init()
        if (mType == TYPE_PIC) {
            mViewModel.getWebsiteLogo()
        } else if (mType == TYPE_VIDEO){
            mViewModel.getWebsiteVideoDetail()
        }
    }

    private fun showAvatar(avatar: String) {
        mUpLoadPic = avatar
        if (TextUtils.isEmpty(avatar)) {
            mBinding.ivDelete.visibility = View.GONE
            mBinding.ivVideo.visibility = View.GONE
            mBinding.ivPic.setImageResource(R.drawable.img_pic_bg)
        } else {
            mBinding.ivDelete.visibility = View.VISIBLE
            mBinding.ivVideo.visibility = View.GONE
            //Glide展示图片
            Glide.with(this) //加载设置宽高限制
                .load("$avatar?x-oss-process=image/resize,m_fixed,h_100") //显示圆图
                //                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                //设置为头像
                .into(mBinding.ivPic)
        }
    }


    // 图片结果回调
    override fun onPictureSelectorResult(selectList: List<LocalMedia>) {
        // 获取到图片的本地路径
        val path = selectList[0].compressPath
        //保存在文件中
        if (!TextUtils.isEmpty(path)) {
            val file = File(path)
            //接口上传文件
            mViewModel.uploadAvatar(file)
        } else {
            MToast.showToast(this, "获取图片失败！")
        }
    }


    fun videoSelector(number: Int, requestCode: Int) {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofVideo())
            .imageEngine(GlideEngine.createGlideEngine())
            .selectionMode(PictureConfig.MULTIPLE)
            .isCompress(true) //是否压缩
            .minimumCompressSize(10240) //小于10M不压缩
            .maxSelectNum(number) //判断还能选多少张图片
            .forResult(requestCode)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) return
        when (requestCode) {
            336 -> {
                val selectList1 = PictureSelector.obtainMultipleResult(data)
                if (selectList1 != null && selectList1.isNotEmpty()) {
                    localVideoUrl = selectList1[0].realPath
                    videoCoverUrl = selectList1[0].realPath
                    DialogHelper.showProgressDialog(
                        this@UpLoadActivity,
                        null,
                        "数据加载中...",
                        0,
                        false,
                        false,
                        null
                    ).setCanceledOnTouchOutside(false)
                    mViewModel.getVideoParamsSTS(localVideoUrl)
                }
            }
        }
    }

    /*
     * 请求上传视频返回的数据
     * */
    fun uploadVideoResult(videoId: String) {
        mUploadVideo = videoId
        runOnUiThread {
            if (!TextUtils.isEmpty(videoCoverUrl)) {
                Glide.with(this)
                    .asBitmap()
                    .load(videoCoverUrl)
                    .apply(RequestOptions().placeholder(R.drawable.null_img_list))
                    .into(object : SimpleTarget<Bitmap>() {
                        override fun onResourceReady(
                            resource: Bitmap,
                            transition: Transition<in Bitmap>?
                        ) {
                            mBinding.ivPic.setImageBitmap(resource)
                        }

                    })
                mBinding.ivDelete.visibility = View.VISIBLE
                mBinding.ivVideo.visibility = View.VISIBLE
                mBinding.ivVideo.setOnClickListener { v ->
                    WebsiteUtils.getInstance().openVideo(this, videoId, localVideoUrl, videoCoverUrl)
                }
            } else {
                mBinding.ivDelete.visibility = View.GONE
                mBinding.ivVideo.visibility = View.GONE
                mBinding.ivPic.setImageResource(R.drawable.img_pic_bg)
            }
        }
    }

}